package com.atguigu.gmall.ums.service.impl;

import com.alibaba.nacos.common.utils.MD5Utils;
import com.atguigu.gmall.common.exception.GmallUserException;
import com.atguigu.gmall.common.utils.RegexValidateUtils;
import com.atguigu.gmall.ums.vo.UserRegisterVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import java.util.UUID;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.common.bean.PageResultVo;
import com.atguigu.gmall.common.bean.PageParamVo;

import com.atguigu.gmall.ums.mapper.UserMapper;
import com.atguigu.gmall.ums.entity.UserEntity;
import com.atguigu.gmall.ums.service.UserService;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {

    @Override
    public PageResultVo queryPage(PageParamVo paramVo) {
        IPage<UserEntity> page = this.page(
                paramVo.getPage(),
                new QueryWrapper<UserEntity>()
        );

        return new PageResultVo(page);
    }

    @Override
    public Boolean check(String data, Integer type) {
        LambdaQueryWrapper<UserEntity> queryWrapper = Wrappers.lambdaQuery(UserEntity.class);
        //1，用户名；2，手机；3，邮箱
        switch (type){
            case 1:
                queryWrapper.eq(UserEntity::getUsername , data);
                break;
            case 2:
                queryWrapper.eq(UserEntity::getPhone , data);
                break;
            case  3:
                queryWrapper.eq(UserEntity::getEmail , data);
                break;
        }
        return this.count(queryWrapper)==0;
    }

    @Override
    public void register(UserRegisterVO userRegisterVO) {
        //1、参数校验：必须参数不能为空、格式满足要求
        String code = userRegisterVO.getCode();
        String email = userRegisterVO.getEmail();
        String password = userRegisterVO.getPassword();
        String phone = userRegisterVO.getPhone();
        String username = userRegisterVO.getUsername();
        if(StringUtils.isEmpty(username)||
            StringUtils.isEmpty(password)||
                !RegexValidateUtils.checkCellphone(phone)
            ){
            throw new GmallUserException("注册信息填写错误",4);
        }
        //2、注册验证码校验
        //3、密码加密
        //MD5: 相同明文每次加密的结果一样 得到32位长度的16进制数字组成的字符串，属于不可逆加密
        // md5加密的密码校验： 用户注册时加密保存，用户登录时提交的明文再次加密和数据库密文比较
        //    容易被暴力破解
        //    解决： 为每个用户生成一个唯一字符串， 用户提交的明文使用Md5加密后+ 唯一字符串再次加密 保存
        String salt = UUID.randomUUID().toString().substring(0,6);
        String encodePwd = MD5Utils.md5Hex(MD5Utils.md5Hex(password,"UTF-8")+salt,"UTF-8");

        //4、保存数据到数据库
        UserEntity user = new UserEntity();
        user.setUsername(username);
        user.setPassword(encodePwd);
        user.setSalt(salt);
        user.setEmail(email);
        user.setPhone(phone);
        user.setIntegration(0);
        user.setGrowth(0);
        user.setLevelId(1L);
        user.setNickname("谷粉_"+UUID.randomUUID().toString().substring(0,6));
        user.setHeader("https://c-ssl.dtstatic.com/uploads/blog/202103/31/20210331160001_9a852.thumb.1000_0.jpg");
        user.setStatus(1);//0 账户正常  1 锁定
        user.setCreateTime(new Date());
        user.setSourceType(1);//1: web端  2：android   3：ios  4：小程序
        this.save(user);
    }

    @Override
    public UserEntity queryUser(String loginName, String password) {
        //用户名/手机号/邮箱
        //1、查询登录名称对应的用户
        UserEntity userEntity = this.getOne(Wrappers.lambdaQuery(UserEntity.class)
                .eq(UserEntity::getUsername, loginName)
                .or()
                .eq(UserEntity::getPhone, loginName)
                .or()
                .eq(UserEntity::getEmail, loginName));
        if(userEntity==null){
            throw new GmallUserException("账户输入有误" , 2);
        }
        //2、判断查询到的用户密码 和明文密码加密后的结果是否一致
        String encodePwd = userEntity.getPassword();
        String salt = userEntity.getSalt();
        String pwd = MD5Utils.md5Hex(MD5Utils.md5Hex(password, "UTF-8") + salt, "UTF-8");
        if(!encodePwd.equals(pwd)){
            throw new GmallUserException("密码错误",3);
        }
        //设置返回的用户对象密码为空 避免密码泄露
        userEntity.setSalt(null);
        userEntity.setPassword(null);

        return userEntity;
    }

}